package com.wutong.erb.util;

import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.io.File;
import java.io.FileReader;
import java.util.Date;

/**
 * 邮箱工具类
 * @author wutong
 */
@Slf4j
public class EmailUtil {

    public static SimpleMailMessage buildSimpleEmail(String from, String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setSentDate(new Date());
        return message;
    }

    public static SimpleMailMessage buildSimpleEmail(String from, String to, String subject, File htmlContent) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        StringBuilder content = new StringBuilder();
        try (FileReader reader = new FileReader(htmlContent)) {
            int ch;
            while ((ch = reader.read()) != -1) {
                content.append((char) ch);
            }
        } catch (Exception e) {
            log.error("读取html文件失败", e);
        }
        message.setText(content.toString());
        message.setSentDate(new Date());
        return message;
    }

    public static boolean asyncSendEmail(JavaMailSender mailSender, MimeMessage message) {
        try {
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            log.error("发送邮件失败", e);
            return false;
        }
    }
}
